<template>
	<el-col :span="24" class="All">
		<el-col :span="24" class="TableInfo">
			<div class="container">
				<el-col :span="4" v-if="this.postData.opera != 'DBTotal'">
					<el-col :span="8" style="
              display: grid;
              align-items: center;

              height: 30px;
            ">请选择IP:</el-col>

					<el-col :span="15">
						<el-select v-model="selectItem" filterable placeholder="请输入ip" :loading="loadings"
							@change="selectIp" ref="select">
							<el-option v-for="item in options" :key="item.value" :label="item.label"
								:value="item.value">
								<span style="float: left">{{ item.label }}</span>
								<span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.dbSid
                }}</span>
							</el-option>
						</el-select>
					</el-col>
				</el-col>

				<el-col :span="4" v-else>
					<el-col :span="8" style="
              display: grid;
              align-items: center;

              height: 30px;
            ">请选择IP:</el-col>

					<el-col :span="15">
						<el-select v-model="selectDBTotal" filterable placeholder="请输入ip" @change="ChangeDBTotal"
							ref="select">
							<el-option v-for="(item,index) in DBTotalOptions" :key="item.value+index"
								:label="item.label" :value="item.value">
								<span style="float: left">{{ item.label }}</span>
								<span style="float: right;padding-left:15px;color: #8492a6; font-size: 12px">{{
                  item.DBservername
                }}</span>
							</el-option>
						</el-select>
					</el-col>
				</el-col>

				<el-col :span="20">
					<v-historyToolBar :fullPath="postData.opera" :tableColumns="tableColumns" @changeLie="getChangeLie"
						@pickerDate="getPickerDate" @selectOpera="getSelectOpera" @inputFilter="getInputFilter"
						:operaOption="operaOption" :tableData="tableData" :tableDataFields="tableDataFieldsFn"
						@exportData="exportData" :isShowfre="false" :fileName="fileName" @goSearch="initDbTotalData">
					</v-historyToolBar>
				</el-col>
				<!-- <div v-if="postData.opera != 'DBTotal'"> -->
				<div>
					<el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
						:data="tableDataFn" border stripe style="width: 100%">
						<el-table-column type="index" width="50" label="序号"> </el-table-column>
						<template v-for="item in tableColumns">
							<el-table-column :prop="item.prop" :label="item.label" :width="item.width" align="center"
								v-if="item.isShow" :key="item.prop">
								<template v-slot="scope">
									<template v-if="item.format == 'STARTDATA'">
										{{
                      scope.row[item.prop] == null
                        ? 0
                        : Number(scope.row[item.prop].toFixed(2))
                    }}
									</template>
									<template v-else-if="item.format == 'ENDDATA'">
										{{
                      scope.row[item.prop] == null
                        ? 0
                        : Number(scope.row[item.prop].toFixed(2))
                    }}
									</template>
									<template v-else-if="item.format == 'GROWTH'">
										{{
                      scope.row[item.prop] == null
                        ? 0
                        : Number(scope.row[item.prop].toFixed(2))
                    }}
									</template>
									<template v-else>
										<div>
											{{ scope.row[item.prop] }}
										</div>
									</template>
								</template>
							</el-table-column>
						</template>
					</el-table>
					<v-pagination :dataTotal="dataTotal" :curPage="postData.curPage" :pageSize="postData.pageSize"
						@getCurPage="getPaginationCurPage" @getPageSize="getPaginationPageSize">
					</v-pagination>
				</div>
				<!-- <div v-else class="DBTotalData">
         
          <el-descriptions
          
          direction="vertical"
          :column="2"
          border
        >
          <el-descriptions-item label="IP" >{{DBTotalData['ip']}}</el-descriptions-item>
          <el-descriptions-item label="数据服务器名称" >{{DBTotalData['DBservername']}}</el-descriptions-item>
          <el-descriptions-item label="开始数据(G)" >{{DBTotalData['start data']}}</el-descriptions-item>
          <el-descriptions-item label="结束数据(G)" >{{DBTotalData['end data']}}</el-descriptions-item>
          <el-descriptions-item label="增长(G)" >{{DBTotalData['growth']}}</el-descriptions-item>
        </el-descriptions>
        </div> -->
			</div>
		</el-col>
	</el-col>
</template>

<script>
	import {
		fetchData,
		exportData,
		Testseledb,
		tableSall
	} from "@/api/index.js";
	import vPagination from "common/Pagination.vue";
	import vHistoryToolBar from "historyData/HistoryToolBarDB.vue";
	import DbTableSpaceTableColumns from "historyData/dataBase/dbOracle/DbTableSpaceTableColumns.js";
	import DbAsmGroupTableColumns from "historyData/dataBase/dbOracle/DbAsmGroupTableColumns.js";
	import DBTotalTableColumns from "historyData/dataBase/dbOracle/DbTotal.js";
	import downloadFile from "@/plugs/downloadFile.js";
	import dateFormat from "@/plugs/dateFormat.js";

	export default {
		components: {
			vPagination,
			vHistoryToolBar,
		},
		data() {
			return {
				postData: {
					opera: "",
					curPage: 1,
					pageSize: 20,
					filtersType: "fuzzyquery",
					filters: {
						monid: "",
						StartTime: "",
						EndTime: "",
						ip: "",
						// "Tablespace_Name": ""
					},
				},
				fileName: "",
				infoItem: "",
				selectIteminfo: "",
				tableData: [],
				dataTotal: 0,
				tableColumns: [],
				searchJson: {},
				operaOption: [{
						label: "总数据量",
						value: "DBTotal",
						filter: ""
					},
					{
						label: "表空间",
						value: "DBTablespaceHistory",
						filter: {
							TABLESPACE_NAME: "指定表空间名..."
						},
					},
					{
						label: "ASM",
						value: "DBAsmGroupHistory",
						filter: ""
					},
				],
				operaColumns: {
					DBTablespaceHistory: DbTableSpaceTableColumns,
					DBAsmGroupHistory: DbAsmGroupTableColumns,
					DBTotal: DBTotalTableColumns,
				},
				postSearchData: {
					opera: "dbConnect",
					curPage: 1,
					pageSize: 20,
					sort: {
						sortColumn: "",
						sortOrders: "",
					},
					filtersType: "fuzzyquery",
					filters: {},
				},
				columns: [],
				TextDatabace: {},
				searchIP: "",
				seleItem: {},
				options: "",
				list: [],
				selectItem: "",
				loadings: false,
				loading: false,
				exportOption: {
					DBTablespaceHistory: {
						url: "Sp/excMV_db_tablespace",
						fileName: "表空间",
					},
					DBAsmGroupHistory: {
						url: "",
						fileName: "ASM",
					},
					DBTotal: {
						url: "",
						fileName: "总数据量",
					},
				},
				DBTotalData: {},
				selectDBTotal: "",
				DBTotalOptions: [],
			};
		},
		created() {
			this.getSearchData();
		},
		computed: {
			// columnsFn() {
			// 	return this.columns.filter((d) => {
			// 		if (d.ip.includes(this.searchIP)) {
			// 			d['selected'] = false;
			// 			// if (d.MONID == this.postData.filters.monid) {
			// 			// 	d['selected'] = true;
			// 			// }
			//             	if (d.cid == this.postData.filters.monid) {
			// 				d['selected'] = true;
			// 			}

			// 			return d;
			// 		}
			// 	});
			// },
			tableDataFn() {
				if (this.postData.opera == "DBTotal") {
					if (this.tableData) {
						return this.tableData.filter((item) => {
							return item.ip ? (item.ip + "-" + item.DBservername + "-" + item['start data'] + "-" +
								item['end data']).includes(this.selectDBTotal) : ''

						});
					}
				} else {
					return this.tableData;
				}
			},
			tableDataFieldsFn() {
				let _jsonfields = {};
				this.tableColumns.filter((item) => {
					if (item.isShow) {
						_jsonfields[item.label] = item.prop;
					}
				});

				return _jsonfields;
			},
		},
		mounted() {
			this.$refs.select.$el.onpaste = () => {
				return false;
			};
		},
		methods: {
			getSearchData() {
				Testseledb().then((res) => {
					this.columns = res.data;
					this.list = this.columns.map((item) => {
						return {
							value: item.cid,
							label: item.ip,
							monid: item.cid,
							dbSid: item.dbSid,
						};
					});

					this.options = this.list;
					if (this.columns.length > 0) {
						this.dbClickFirst();
					}
				});
			},

			TalallColorMethod(percentage) {
				if (percentage <= 50) {
					return "#67c23a";
				} else if (percentage <= 75) {
					return "#e6a23c";
				} else {
					return "#f56c6c";
				}
			},

			dbClickFirst() {
				this.selectItem = this.columns[0].ip;
				this.selectIteminfo = this.columns[0];
				this.initDbTotalData();
			},
			getTableData() {
				this.loading = true;

				fetchData({
					postData: JSON.stringify(this.postData),
				}).then((res) => {
					this.tableColumns = this.operaColumns[this.postData.opera];
					this.dataTotal = res.dataTotal;
					this.tableData = res.data;
					this.loading = false;
					this.$message({
						message: '请求成功',
						type: 'success',
						duration: 1000
					})
				});
			},
			initDbTotalData() {
				this.loading = true;


				if (this.postData.opera == "DBTotal") {
					if (Array.isArray(this.selectIteminfo)) {
						this.selectIteminfo = this.selectIteminfo[0];
					}

					if (this.postData.filters.StartTime && this.postData.filters.EndTime) {
						this.loading = true;
						tableSall({
								time: this.postData.filters.StartTime,
								time2: this.postData.filters.EndTime,
							})
							.then((res) => {
								this.tableColumns = this.operaColumns[this.postData.opera];
								if (res) {

									this.tableData = res;
									this.DBTotalOptions = res.map((item, index) => {
										return {
											//确保value 唯一
											value: item.ip + "-" + item.DBservername + "-" + item[
												'start data'] + "-" + item['end data'],
											label: item.ip,
											DBservername: item.DBservername
										};
									});
									this.DBTotalOptions.unshift({
										value: "",
										label: "全部",
									});
									this.dataTotal = 0;
									this.$message({
										message: '请求成功',
										type: 'success',
										duration: 1000
									});
									// this.DBTotalData = res
								}
							})
							.catch((err) => {
								console.log(err);
							})
							.finally((_) => {
								this.loading = false;
							});
					}

				} else {
					if (!this.postData.filters.monid) {
						this.$message({
							type: 'error',
							message: "请选择IP节点",
							duration: 4000

						});
						this.tableData = [];
					} else {
						this.getTableData();
					}
				}
			},

			getPaginationCurPage(val) {
				this.postData.curPage = val;

				this.getTableData();
				this.initDbTotalData();
			},
			getPaginationPageSize(val) {
				// 分页大小改变之后，重置当前页码为 1
				this.postData.curPage = 1;
				this.postData.pageSize = val;

				this.getTableData();
				this.initDbTotalData();
			},
			getChangeLie(val) {
				// 遍历表格列
				this.tableColumns.map((item, index) => {
					// 列的显示隐藏状态改变
					item.isShow = val.includes(item.label);
				});
			},
			// 获取子组件选择的时间
			getPickerDate(pickerDate) {
				this.postData.curPage = 1;
				for (const key in pickerDate) {
					this.postData.filters[key] = pickerDate[key];
				}

			},
			getSelectOpera(item) {
				this.postData.curPage = 1;
				this.postData.opera = item.value;
				// 删除后台可能无法识别的 filters 条件
				for (const key in this.postData.filters) {
					if (key != "monid" && key != "StartTime" && key != "EndTime") {
						delete this.postData.filters[key];
					}
				}
				if (this.postData.opera == "DBTotal") {
					this.initDbTotalData();
				} else {
					this.postData.filters.monid = this.selectIteminfo.cid
					this.getTableData();
				}
			},
			getInputFilter(data) {
				this.postData.curPage = 1;
				for (const key in data) {
					if (data.hasOwnProperty(key)) {
						const element = data[key];
						this.postData.filters[key] = element;
					}
				}
			},
			exportData(data) {
				if (Array.isArray(this.selectIteminfo)) {
					this.selectIteminfo = this.selectIteminfo[0];
				}
				let _url = this.exportOption[data.type].url;
				let _name = this.exportOption[data.type].fileName == "总数据量" ? '全部' : this.selectIteminfo.ip;
				let _fileName =
					"【" +
					_name +
					"】" +
					this.exportOption[data.type].fileName +
					".xls";

				this.fileName = _fileName;
				// let _data = {
				// 	ip: this.selectIteminfo.ip,
				// 	time: this.postData.filters.StartTime,
				// 	time2: this.postData.filters.EndTime,
				// };

				// exportData(_url, _data)
				// 	.then((res) => {
				// 		// const _blob = new Blob([res], { type: res.type });
				// 		// const _downElement = document.createElement('a');
				// 		// const _href = URL.createObjectURL(_blob);
				// 		// _downElement.href = _href;  // 下载的链接

				// 		// const _timeStamp = new Date().toString();
				// 		// const _nameStr = _timeStamp;
				// 		// _downElement.download = _nameStr;   // 文件名

				// 		// _downElement.click();   // 点击下载
				// 		// URL.revokeObjectURL(_href);    // 释放 blob 对象

				// 		downloadFile(res, _fileName);
				// 	})
				// 	.catch((err) => {
				// 		this.$message.error({
				// 			message: '导出文件失败：' + _fileName,
				// 		});
				// 	});
			},
			selectIp() {
				this.postData.filters.monid = this.selectItem;

				this.selectIteminfo = this.columns.filter(
					(item, index, array) => item.cid == this.selectItem
				);
				this.getTableData()
			},
			ChangeDBTotal(item) {
				// this.initDbTotalData()
				// console.log(item);
			},
		},
		watch: {},
	};
</script>

<style scoped>
	.el-table .warning-row {
		background: oldlace;
	}

	.el-table .success-row {
		background: #f0f9eb;
	}

	.spanInfo {
		padding-right: 10px !important;
	}

	.searchIP {
		padding-bottom: 10px;
	}

	.textLable>>>.el-button+.el-button {
		margin-left: 0px !important;
	}

	.IpButton {
		width: 100%;
		font-size: 14px;
	}

	.textLable .IpButton.selected {
		color: #fff;
		background-color: rgba(64, 158, 255);
	}

	.DBTotalData {
		/* height: 80vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center; */
	}
</style>